import { reqlogin } from "../../http/api"
import { Toast } from "antd-mobile"

//state
const initState={
    user:{
        phone:'',
        password:''
    },
    userInfo: sessionStorage.getItem("userInfo") ? JSON.parse(sessionStorage.getItem("userInfo")) : {}
}
const TYPES = {
    //修改user
    LOGIN_CHANGE_USER: "LOGIN_CHANGE_USER",
    //userinfo
    LOGIN_CHANGE_USER_INFO: "LOGIN_CHANGE_USER_INFO"
}
//reducer
const reducer = (state=initState,action)=>{
    switch (action.type){
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
            //userInfo
            case TYPES.LOGIN_CHANGE_USER_INFO:
                return {
                    ...state,
                    userInfo: action.userInfo
                }
            default:
                return state;

    }
}
//action creator
export const actions = {
    // 修改user
    changeUser: (key, value) => ({ type: TYPES.LOGIN_CHANGE_USER, key, value }),
    //修改 userInfo
    changeUserInfo:userInfo=>{
        if (userInfo.token) {
            sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
        } else {
            sessionStorage.removeItem("userInfo")
        }
        return { type: TYPES.LOGIN_CHANGE_USER_INFO, userInfo: userInfo }
    },
    //登录的逻辑
    doLogin:(push)=>{
        return (dispatch,getState)=>{
            reqlogin(getUser(getState())).then(res => {
                if (res.data.code == 200) {
                    //弹成功
                    Toast.show({
                        content: res.data.msg
                    })
                    // 存用户信息 res.data.list
                    dispatch(actions.changeUserInfo(res.data.list))

                    //跳转页面
                    push("/index/home")

        }

    })
}

}
}
//导出信息
//user
export const getUser = state=>state.login.user;
//userInfo
export const getUserInfo = state => state.login.userInfo;

//导出reducer
export default reducer;
